/*
 * @lc app=leetcode.cn id=15 lang=javascript
 *
 * [15] 三数之和
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
  const res = []
  if (nums.length < 3) {
    return res
  }
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length; i++){
    if (nums[i] > 0) {
       break
    }
    if (i > 0 && nums[i] === nums[i - 1]) {
      continue
    }
    let start = i + 1
    let end = nums.length - 1
    while (start < end) {
      const sum = nums[start] + nums[end]+nums[i]
      if (sum > 0) {
        end--
      } else if (sum < 0) {
        start++
      } else {
        res.push([nums[start], nums[end], nums[i]])
        while (start < end && nums[start] === nums[start + 1]) {
          start++
        }
        while (start < end && nums[end] == nums[end - 1]) {
          end--
        }
        end--
        start++
      }
    }
  }
  return res
};
// @lc code=end

